package org.jeecg.modules.demo.moenydata.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.formula.functions.T;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.moenydata.entity.Moneydatahappycafe;
import org.jeecg.modules.demo.moenydata.entity.ReturnData;
import org.jeecg.modules.demo.moenydata.service.IMoneydatahappycafeService;

import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.moenydata.uitils.*;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 开心网吧提现
 * @Author: jeecg-boot
 * @Date:   2021-03-04
 * @Version: V1.0
 */
@Api(tags="开心网吧提现")
@RestController
@RequestMapping("/moenydata/moneydatahappycafe")
@Slf4j
public class MoneydatahappycafeController extends JeecgController<Moneydatahappycafe, IMoneydatahappycafeService> {
	@Autowired
	private IMoneydatahappycafeService moneydatahappycafeService;

	 @Autowired
	 private RedisTemplate redisTemplate;


	@Autowired
	private ExcleUtil excleUtil;

	//private String callBackNum="http://192.168.1.85:8088/back";
	private String callBackNum="http://wzyx.5idhf.com:11200/back";
	/**
	 * 分页列表查询
	 *
	 * @param moneydatahappycafe
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "开心网吧提现-分页列表查询")
	@ApiOperation(value="开心网吧提现-分页列表查询", notes="开心网吧提现-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Moneydatahappycafe moneydatahappycafe,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   @RequestParam(name = "num",defaultValue="301",required = false) String num,
								   HttpServletRequest req) {
		String tbName=GamesEnum.getTableName(num);

		if(tbName.equals("erro")){
			return Result.error("没有对应该参数的库表!");
		}
		tbName+="moneydata";
		Map<String, String[]> parameterMap=req.getParameterMap();
		moneydatahappycafe=queryMap(parameterMap);
         //循环遍历
		/*
		for(String key:parameterMap.keySet()){
			String value = parameterMap.get(key)[0].toString();//
			System.out.println("key:"+key+" vlaue:"+value);
		}*/

		/*QueryWrapper<Moneydatahappycafe> queryWrapper = QueryGenerator.initQueryWrapper(moneydatahappycafe, req.getParameterMap());
		Page<Moneydatahappycafe> page = new Page<Moneydatahappycafe>(pageNo, pageSize);
		IPage<Moneydatahappycafe> pageList = moneydatahappycafeService.page(page, queryWrapper);*/
		moneydatahappycafe.setPageNo(pageNo*pageSize-pageSize);
		moneydatahappycafe.setPageSize(pageSize);
		log.info(moneydatahappycafe.getPageNo().toString()+","+moneydatahappycafe.getPageSize().toString());
		//tableName不能为空，会报错
		moneydatahappycafe.setTableName(tbName);
		List<Moneydatahappycafe> pageList=moneydatahappycafeService.getListPage(moneydatahappycafe);
		for(int i=0;i<pageList.size();i++){
			String str=String.valueOf(pageList.get(i).getData());
			if(str!=null&&!str.equals("")&&!str.equals("null")){
			ReturnData data= JSONObject.parseObject(str,ReturnData.class);
			String retxt=data.getReturn_code()+":"+data.getReturn_msg()+","+data.getErr_code();
			pageList.get(i).setData(retxt);
			}
		}
		Integer total=moneydatahappycafeService.getListPageCount(moneydatahappycafe);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("records",pageList);
		map.put("total",total);
		return Result.OK(map);
	}
	
	/**
	 *   添加
	 *
	 * @param moneydatahappycafe
	 * @return
	 */
	/*@AutoLog(value = "开心网吧提现-添加")
	@ApiOperation(value="开心网吧提现-添加", notes="开心网吧提现-添加")
	@PostMapping(value = "/add",produces = "application/json;charset=utf-8")
	public Result<?> add(@RequestBody Moneydatahappycafe moneydatahappycafe) {
		//JSONObject jsonObect = new JSONObject(moneydatahappycafe.getData());

		try {
			Moneydatahappycafe moneydatahappycafe2= moneydatahappycafe;
			//时间格式转时间戳
			moneydatahappycafe2.setRegtime(dateToStamp(moneydatahappycafe2.getRegtime()));
			moneydatahappycafe2.setLogintime(dateToStamp(moneydatahappycafe2.getLogintime()));
			moneydatahappycafe2.setTtime(dateToStamp(moneydatahappycafe2.getTtime()));
			moneydatahappycafe2.setDtime(dateToStamp(moneydatahappycafe2.getDtime()));

			//json转string
			String ddd = moneydatahappycafe.getData().toString();
			moneydatahappycafe2.setData(ddd);
			moneydatahappycafeService.save(moneydatahappycafe2);
		}catch (Exception e){
			e.printStackTrace();
		}

		return Result.OK("添加成功！");
	}*/

	 /**
	  *   添加
	  * @param num 通过id判断实际使用的表
	  * @param param
	  * @return
	  */
	 @AutoLog(value = "开心网吧提现-对接前端")
	 @ApiOperation(value="开心网吧提现-添加对接前端", notes="开心网吧提现-添加对接前端")
	 @PostMapping(value = "/addJson",produces = "application/json;charset=utf-8")
	 public Result<?> addJson(@RequestBody String param,@RequestParam(value="num", required = false) String num) {
		 //log.info("ts:"+id);
		 //获取实际使用表名
		 String dataName= GamesEnum.getTableName(num);
		 if(dataName.equals("erro")){
			 return Result.error("没有对应该参数的库表!");
		 }
		 dataName+="moneydata";
		 //json解密
		 String tx=AesUtils.decrypt(param,"sb0EBogkG4IVSg1u");
		 JSONObject jsontx=JSON.parseObject(tx);
		 //新增数据 写入操作
		 try {
		 	//获取源数据id-对应本地库sourceid
         String soureid= jsontx.getString("Id");
         JSONArray jsonArr=new JSONArray();
         if(soureid.indexOf("[")!=-1){
			 jsonArr= JSONArray.parseArray(soureid);
		 }else{
			 jsonArr.add(soureid);
		 }
			 int number=0;
			 Moneydatahappycafe moneydatahappycafe2=(Moneydatahappycafe)JSONObject.toJavaObject(jsontx,Moneydatahappycafe.class);
			 //设置实际表名
			 moneydatahappycafe2.setTableName(dataName);
		 for(int i=0;i<jsonArr.size();i++){
			  number=moneydatahappycafeService.isActive(jsonArr.get(i).toString(),dataName);
			 	//获取源数据判断是否修改源数据还是新增
			  if(number!=0){
				  moneydatahappycafe2.setSourceid(jsonArr.get(i).toString());
				  moneydatahappycafe2.setDtime(String.valueOf(new Date().getTime()));
				  //json转string
				  if(moneydatahappycafe2.getData()!=null){
					  String jsonData = moneydatahappycafe2.getData().toString();
					  moneydatahappycafe2.setData(jsonData);
				  }
				  moneydatahappycafeService.changeState(moneydatahappycafe2);
			  }else{
				  moneydatahappycafe2.setId(null);
				  moneydatahappycafe2.setSourceid(jsonArr.get(i).toString());

				  //时间格式转时间戳
				  moneydatahappycafe2.setRegtime(TimeUtil.dateToStamp(moneydatahappycafe2.getRegtime()));
				  moneydatahappycafe2.setLogintime(TimeUtil.dateToStamp(moneydatahappycafe2.getLogintime()));
				  moneydatahappycafe2.setTtime(TimeUtil.dateToStamp(moneydatahappycafe2.getTtime()));
				  moneydatahappycafe2.setDtime(TimeUtil.dateToStamp(moneydatahappycafe2.getDtime()));
				  //json转string
				  if(moneydatahappycafe2.getData()!=null){
					  String jsonData = moneydatahappycafe2.getData().toString();
					  moneydatahappycafe2.setData(jsonData);
				  }
				  //moneydatahappycafeService.save(moneydatahappycafe2);
				  //moneydatahappycafeService.saveEntiy(moneydatahappycafe2);
				  redisTemplate.opsForList().leftPush("moneyData", moneydatahappycafe2);
			  }
			  Thread.sleep(100);
		 }
         //log.info("测试输出:"+moneydatahappycafe2.getSourceid());
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error("数据发生异常！");
		 }

		 return Result.OK("操作成功!");
	 }
	
	/**
	 *  编辑
	 *
	 * @param moneydatahappycafe
	 * @return
	 */
	/*@AutoLog(value = "开心网吧提现-编辑")
	@ApiOperation(value="开心网吧提现-编辑", notes="开心网吧提现-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody Moneydatahappycafe moneydatahappycafe) {
		try {
			Moneydatahappycafe moneydatahappycafe2= moneydatahappycafe;
			//时间格式转时间戳
			moneydatahappycafe2.setRegtime(dateToStamp(moneydatahappycafe2.getRegtime()));
			moneydatahappycafe2.setLogintime(dateToStamp(moneydatahappycafe2.getLogintime()));
			moneydatahappycafe2.setTtime(dateToStamp(moneydatahappycafe2.getTtime()));
			moneydatahappycafe2.setDtime(dateToStamp(moneydatahappycafe2.getDtime()));
			moneydatahappycafeService.updateById(moneydatahappycafe2);
		}catch (Exception e){
			e.printStackTrace();
		}


		return Result.OK("编辑成功!");
	}*/
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	/*@AutoLog(value = "开心网吧提现-通过id删除")
	@ApiOperation(value="开心网吧提现-通过id删除", notes="开心网吧提现-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		moneydatahappycafeService.removeById(id);
		return Result.OK("删除成功!");
	}*/

	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	/*@AutoLog(value = "开心网吧提现-批量删除")
	@ApiOperation(value="开心网吧提现-批量删除", notes="开心网吧提现-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.moneydatahappycafeService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}*/

	 /**
	  *   通过id拒绝提现
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "开心网吧提现-通过id拒绝提现")
	 @ApiOperation(value="开心网吧提现-通过id拒绝提现", notes="开心网吧提现-通过id拒绝提现")
	 @GetMapping(value = "/auditNo")
	 public Result<?> auditNo(@RequestParam(name="id",required=true) String id) {
		 List listId=Arrays.asList(id);
		 String str=auditMoney(listId,2);//2批准，4拒绝
		 //加密json
		 String strMi=AesUtils.encrypt(str,"sb0EBogkG4IVSg1u");
		 RestTemplate restTemplate=new RestTemplate();
		 String result=restTemplate.postForObject(callBackNum,strMi,String.class);
		 //moneydatahappycafeService.auditNo(id);
		 return Result.OK("操作成功!");
	 }


	 /**
	  *  批量拒绝提现
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "开心网吧提现-批量拒绝提现")
	 @ApiOperation(value="开心网吧提现-批量拒绝提现", notes="开心网吧提现-批量拒绝提现")
	 @GetMapping(value = "/auditNoBatch")
	 public Result<?> auditNoBatch(@RequestParam(name="ids",required=true) String ids) {
		 List listId=Arrays.asList(ids.split(","));
		 String str=auditMoney(listId,4);//2批准，4拒绝
		 //加密json
		 String strMi=AesUtils.encrypt(str,"sb0EBogkG4IVSg1u");
		 RestTemplate restTemplate=new RestTemplate();
		 String result=restTemplate.postForObject(callBackNum,strMi,String.class);
		 //moneydatahappycafeService.auditNoBatch(listId);
		 return Result.OK("批量拒绝提现成功!");
	 }

	 /**
	  *   通过id通过提现
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "开心网吧提现-通过id通过提现")
	 @ApiOperation(value="开心网吧提现-通过id通过提现", notes="开心网吧提现-通过id通过提现")
	 @GetMapping(value = "/auditYes")
	 public Result<?> auditYes(@RequestParam(name="id",required=true) String id) {
		 List listId=Arrays.asList(id);
		 String str=auditMoney(listId,2);//2批准，4拒绝
		 //加密json
		 String strMi=AesUtils.encrypt(str,"sb0EBogkG4IVSg1u");
		 RestTemplate restTemplate=new RestTemplate();
		 String result=restTemplate.postForObject(callBackNum,strMi,String.class);
		 //moneydatahappycafeService.auditYes(id);
		 return Result.OK("提现成功!");
	 }


	 /**
	  *  批量通过提现
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "开心网吧提现-批量通过提现")
	 @ApiOperation(value="开心网吧提现-批量通过提现", notes="开心网吧提现-批量通过提现")
	 @GetMapping(value = "/auditYesBatch")
	 public Result<?> auditYesBatch(@RequestParam(name="ids",required=true) String ids) {
	 	 List listId=Arrays.asList(ids.split(","));
		 String str=auditMoney(listId,2);//2批准，4拒绝
		 //加密json
		 String strMi=AesUtils.encrypt(str,"sb0EBogkG4IVSg1u");
		 RestTemplate restTemplate=new RestTemplate();
		 String result=restTemplate.postForObject(callBackNum,strMi,String.class);
		 //moneydatahappycafeService.auditYesBatch(listId);
		 return Result.OK("批量通过提现成功!");
	 }
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	/*@AutoLog(value = "开心网吧提现-通过id查询")
	@ApiOperation(value="开心网吧提现-通过id查询", notes="开心网吧提现-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Moneydatahappycafe moneydatahappycafe = moneydatahappycafeService.getById(id);
		if(moneydatahappycafe==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(moneydatahappycafe);
	}*/

    /**
    * 导出excel
    *
    * @param request
    * @param moneydatahappycafe
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Moneydatahappycafe moneydatahappycafe,
								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								  @RequestParam(name = "num",defaultValue="301",required = false) String num) {
		String tbName=GamesEnum.getTableName(num);

		if(tbName.equals("erro")){
			return null;
		}
		tbName+="moneydata";
		moneydatahappycafe.setTableName(tbName);
		moneydatahappycafe.setPageNo(pageNo*pageSize-pageSize);
		moneydatahappycafe.setPageSize(pageNo*pageSize);
    	List<Moneydatahappycafe> list=moneydatahappycafeService.getListPage(moneydatahappycafe);
    	for(int i=0;i<list.size();i++){
    		list.get(i).setRegtime(TimeUtil.stampToDate(list.get(i).getRegtime()));
			list.get(i).setLogintime(TimeUtil.stampToDate(list.get(i).getLogintime()));
			list.get(i).setTtime(TimeUtil.stampToDate(list.get(i).getTtime()));
			list.get(i).setDtime(TimeUtil.stampToDate(list.get(i).getDtime()));
		}
        return excleUtil.exportXls(request, moneydatahappycafe, Moneydatahappycafe.class, "开心网吧提现",list);
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Moneydatahappycafe.class);
    }



	 public String auditMoney(List id,int num){
	 	 // String str="";
		 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 String day=df.format(new Date());
		 String idStr="[";
		 for(int i=0;i<id.size();i++){
		 	idStr+="\""+id.get(i)+"\"";
		 	if(i!=id.size()-1){
				idStr+=",";
			}
		 }
		 idStr+="]";
		 //根据id获取记录
		 String jsonTxt="{" +
				 "\"id\":" + idStr + "," +
				 "\"state\":" + num + "," +
				 "\"dtime\":\"" + day + "\""+
				 "}";
	 	return jsonTxt;
	 }
	 public Moneydatahappycafe queryMap(Map<String,String[]> parameterMap){
		 Moneydatahappycafe moneydatahappycafe=new Moneydatahappycafe();
		 if(parameterMap.containsKey("uid")){
			 moneydatahappycafe.setUid(parameterMap.get("uid")[0].toString());
		 }
		 if(parameterMap.containsKey("uname")){
			 moneydatahappycafe.setUname(parameterMap.get("uname")[0].toString());
		 }
		 if(parameterMap.containsKey("realname")){
			 moneydatahappycafe.setRealname(parameterMap.get("realname")[0].toString());
		 }
		 if(parameterMap.containsKey("chanid")){
			 moneydatahappycafe.setChanid(parameterMap.get("chanid")[0].toString());
		 }
		 if(parameterMap.containsKey("state")){
			 moneydatahappycafe.setState(String.valueOf(parameterMap.get("state")[0]));
		 }
		 if(parameterMap.containsKey("ttime")){
			 moneydatahappycafe.setTtime(parameterMap.get("ttime")[0].toString());
		 }
		 if(parameterMap.containsKey("dtime")){
			 moneydatahappycafe.setDtime(parameterMap.get("dtime")[0].toString());
		 }

		 return moneydatahappycafe;
	 }

}
